#import MSLogger
import time
import datetime
import pyodbc
import sys
import pdb
RECONF_FILE = 'C:\safe\ms.reconf'
LOG_FILE    = 'C:\safe\ms_config_creator.log'
#MSProcessor.MSLogger.logInit(LOG_FILE, 4, True)

def insert_device_to_CARONLINE(device_params):
    conn = pyodbc.connect(driver='{SQL Server}', server='SRV1\PGSMDATA', port='49177', uid='sa', pwd='q123456*')
    c = conn.cursor()
    c.execute("INSERT INTO PGSMData.dbo._devices (uid) VALUES ('%s')" % (str(device_params[1]))) #device mac
    conn.commit()
    c.execute("SELECT IDENT_CURRENT('PGSMData.dbo._devices')")
    t = c.fetchall()
    device_msid = int(t[0][0])
    device_name = 'dev' + str(device_params[0])
    device_pass = 'pass' + str(device_params[0])
    query = "INSERT INTO PGSMData.dbo._users (login, password, defaultDevice) VALUES ('%s', '%s', '%s')" % (device_name, device_pass, str(device_msid))
    c.execute(query)
    conn.commit()
    device_value = 'login=%s&password=%s&exportSupport=1' % (device_name, device_pass)
    device_ctime = datetime.datetime.fromtimestamp(time.time()).strftime('%d/%m/%Y %H:%M:%S')
    query = "INSERT INTO PGSMData.dbo.Security_values (\"key\", \"value\", \"date\") VALUES ('%s', '%s', '%s')" % (str(device_params[1]), device_value, device_ctime)
    c.execute(query)
    conn.commit()
    conn.close()
    return (device_params[0], device_params[1], device_msid, device_name, device_pass)

def request_params():
    sys.stdout.write('Enter Device Id: \n')
    device_pcnid   = int(sys.stdin.readline().strip('\n'))
    sys.stdout.write('Enter Divice MAC: \n')
    device_mac  = sys.stdin.readline().strip('\n')
    return (device_pcnid, device_mac)

while True:
    try:
        device_params = request_params()
        device_params = insert_device_to_CARONLINE(device_params)
        print 'device successfully added: device_id is %s car-online key is %s\n\n' % (str(device_params[0]), str(device_params[1]))
    except Exception, err:
        print 'device add failed: %s' % (str(err))

